<?php

namespace App\Services\Goods;
use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Common\Tag;
use App\Params\Backend\TagListParams;
use App\Params\Backend\TagUpdateParam;
use App\Services\BaseService;

/**
 * 商品标签相关业务类
 *
 * @package App\Http\Services
 * @author WangBin
 * @date 2021-06-17
 */
class TagService extends BaseService
{
    /**
     * 保存标签
     *
     * @param TagUpdateParam $data
     * @return mixed
     * @throws BusinessException
     */
    public function update(TagUpdateParam $data)
    {
        if($data->getTagId()) {
            $tag = Tag::getById($data->getTagId());
            if(is_null($tag)) {
                throw new BusinessException(ResponseCode::TAG_NOT_FOUND);
            }
        }
        // 校验名称唯一
        $check = Tag::checkName($data->getTagName(), $data->getTagType(), $data->getTagId());
        if($check) {
            throw new BusinessException(ResponseCode::SAVE_FAIL, ['error' => '名称已存在']);
        }
        return Tag::saveData($data);
    }

    /**
     * 标签列表
     *
     * @param TagListParams $filter
     * @return array
     */
    public function getList(TagListParams $filter)
    {
        $tags = Tag::getByFilter($filter);
        return $this->toList($tags, $filter->getPage(), $filter->getPageSize());
    }

    /**
     * 获取标签详情
     *
     * @param int $tagId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws BusinessException
     */
    public function get(int $tagId)
    {
        $tag = Tag::getById($tagId);
        if(is_null($tag)) {
            throw new BusinessException(ResponseCode::TAG_NOT_FOUND);
        }
        return $tag;
    }

    public function enable(int $tagId)
    {
        $tag = Tag::getById($tagId);
        if(is_null($tag)) {
            throw new BusinessException(ResponseCode::TAG_NOT_FOUND);
        }
        $isActive = $tag->is_active == 1 ? 0 : 1;
        return Tag::enable($tagId, $isActive);
    }
}